package com.example.drawabledemoapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

class CustomView extends View {

    List<Path> listStrokes = new ArrayList<Path>();
    Path pathStroke;
    Bitmap mBitmap;
    Paint mPaint;
    Canvas mCanvas;
    boolean mBooleanOnTouch = false;

    float oldX;
    float oldY;

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                pathStroke = new Path();
                pathStroke.moveTo(x, y);
                oldX = x;
                oldY = y;
                mBooleanOnTouch = true;
                listStrokes.add(pathStroke);
                break;
            case MotionEvent.ACTION_MOVE:
                if (mBooleanOnTouch) {
                    pathStroke.quadTo(oldX, oldY, x, y);
                    oldX = x;
                    oldY = y;
                    drawStrokes();
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mBooleanOnTouch) {
                    pathStroke.quadTo(oldX, oldY, x, y);
                    drawStrokes();
                    mBooleanOnTouch = false;
                }
                break;
        }
        return true;
    }

    void drawStrokes() {
        if (mCanvas == null) {
            mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas();
            mCanvas.setBitmap(mBitmap);
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setColor(Color.BLUE);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(5);
        }

        for (Path path : listStrokes) {
            mCanvas.drawPath(path, mPaint);
        }

        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        if (mBitmap != null) {
            canvas.drawBitmap(mBitmap, 0, 0, paint);
        }
    }
}
